﻿package net.wangit.dev.unit;

import net.wangit.Element;
import net.wangit.MapList;
import net.wangit.Row;
import net.wangit.Unit;
import net.wangit.context.ActionContext;
import net.wangit.context.ActionContextHelper;
import net.wangit.dev.ConsoleDomainUtil;
import net.wangit.dev.component.ObjectTreeHelper;
import net.wangit.framework.util.QueryProcessor;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.DBImplementor;
import net.wangit.jdbc.util.DBHelper;
import net.wangit.support.UnitInterceptor;
import net.wangit.util.Checker;
import net.wangit.view.element.component.TextFieldElement;
import net.wangit.view.enumeration.EnumerationFactory;
import net.wangit.view.unit.UnitComponent;

public class FindUnitUI implements UnitInterceptor {

	private static final String SQL = "select * from UNIT order by uid";
	private static final String ICON_PATH = "/domain/dev/u/";
	public static final String KEY = "net.wangit.dev.unit.FindUnitUI.columnName";

	public FindUnitUI() {
	}

	public String intercept(ActionContext ac, Unit unit) throws Exception {
		DB db = DBHelper.getDomainDB(ConsoleDomainUtil.getDomain(ac));
		UnitComponent uc = (UnitComponent) unit;
		String sql = QueryProcessor.addConditionAndOrder(ac,
				(DBImplementor) db, FindUnitUI.SQL, "dev", uc.getQueryUnitId(),
				uc.getTableName(), null);
		MapList data = db.query(sql);
		if (data != null) {
			Element icon = unit.getElement("icon");
			Element uid = unit.getElement("uid");
			for (int i = 0; i < data.size(); i++) {
				Row row = data.getRow(i);
				String link = (new StringBuilder(FindUnitUI.ICON_PATH)).append(
						ObjectTreeHelper.getUnitIcon(db, row.get("uid"), row,
								true)).toString();
				icon.setLink(i, link);
				uid.setLink(i, getUrl(row));
			}

		}
		unit.setData(data);
		String columnName = ActionContextHelper.getRequest2Session(ac,
				"findunit.column", "dev.findunit.column", null);
		if (!Checker.isEmpty(columnName)) {
			MapList list = EnumerationFactory.getEnumeration(ac, "dev",
					"unitcolumn");
			int rowIndex = list.findRowIndex("value", columnName);
			TextFieldElement element = new TextFieldElement();
			element.setId(columnName);
			if (rowIndex >= 0)
				element.setName(list.getRow(rowIndex).get("name"));
			unit.addElement(element);
		}
		return unit.write(ac);
	}

	private String getUrl(Row row) {
		String unitId = row.get("uid");
		int c = row.getInt("c", 1);
		switch (c) {
		case 1:
		case 2:
		case 3:
			return "/dev/unit.do?m=e&uid=" + unitId;
		case 4:
			return "/dev/frameset.do?m=e&uid=" + unitId;
		case 7:
			return "/dev/jr.do?m=e&uid=" + unitId;
		case 5:
		case 6:
		}
		return null;
	}
}
